
<!DOCTYPE html>
<html>
	<head>
		<title>Route Optimizer</title>
		  <!--<link rel="stylesheet" type="text/css" href="style.css" />
-->		  <script src="js/site.js" type="text/javascript"></script>
	</head>

<body>
  <div class="container">
	
	<div class="Content">
	<h1>Element Rides Dropoff Scheduler</h1>
  
		<div class="realContent">
	

  <div id="map" style="width: 0px; height: 0px; visibility:hidden;"> <!--style="width: 780px; height: 600px;-->
    <span style="color:Gray;">Loading map...</span>
  </div>
  <br/>
  <div>
		<p>Type in an address</p>
		<div>
			<input type="text" id="location" style="width:400px;" />
			<input type="button" onclick="AddLocation()" value="Add location"/><br/>
		</div>
		<table id="locations" style="width:100%;">
			<thead>
				<tr>
					<th style="text-align:left;">Location</th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td colspan="4">< Added locations will appear here ></td>
				</tr>
			</tbody>
		</table>
				
		<br/>
		<table>
			<tr>
				<td>
					<input type="button" onclick="ClearPolyLine()" value="Clear"/>
				</td>
				<td>Removes all locations from the map</td>
			</tr>

		</table>
		<input type="button" onclick="GetDirections()" value="Get directions"/><br/>
  </div>
  <div id="directions">
  </div>

  <script src="http://maps.google.com/maps/api/js?libraries=places&sensor=false" type="text/javascript"></script>
  <script type="text/javascript">
    /* <![CDATA[ */
      var latlng = new google.maps.LatLng(37.725976, -122.233764);
      var options = {
        zoom: 12,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        draggableCursor: "crosshair"
      };

			var locationsAdded = 1;
      var map = new google.maps.Map(document.getElementById("map"), options);
      var points = [];
      var markers = [];
		  google.maps.event.addListener(map,"click", function(location) {
        GetLocationInfo(location.latLng, "Location " + locationsAdded);
				locationsAdded++;
      });
      var directionsDisplay = new google.maps.DirectionsRenderer();

			// autocomplete
			var autocomplete = new google.maps.places.Autocomplete(document.getElementById('location'), {});
			google.maps.event.addListener(autocomplete, 'place_changed', function() {
				var place = autocomplete.getPlace();
				GetLocationInfo(place.geometry.location, $('#location').val());
        map.setCenter(place.geometry.location);
        $("#location").val("");
			});
			
      function AddLocation(){
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({address: $("#location").val()}, function(results, status) {
					if (results[0]) {
						var result = results[0];
						var latLong = result.geometry.location;

						GetLocationInfo(latLong, $('#location').val());
						map.setCenter(latLong);
						$("#location").val("");
					}
					else {
						alert("Location not found");
					}
				});
      }

      function GetLocationInfo(latlng, locationName) {
        if (latlng != null) {
					var point = { LatLng: latlng, LocationName: locationName };
          points.push(point);
          BuildPoints();
        }
      }

      function clearMarkers(){
        for (var i=0; i<markers.length; i++) {
          markers[i].setMap(null);
        }
        markers = [];
      }

      function BuildPoints() {
        clearMarkers();

				var html = "";
				
        for (var i=0; i<points.length; i++) {
          var marker = new google.maps.Marker({position: points[i].LatLng, title : points[i].LocationName});
          markers.push(marker);
          marker.setMap(map);
					
					html += "<tr><td>" + points[i].LocationName + "</td><td>" + roundNumber(points[i].LatLng.lat(), 6) + "</td><td>" + 
						roundNumber(points[i].LatLng.lng(), 6) + '</td><td><button class="delete" onclick="removeRow(' + i + 
						');">Delete</button></td><td>';
					if (i < points.length-1)
						html += '<button class="moveDown" onclick="moveRowDown(' + i + ');">Move down</button>';
					html += '</td><td>';
					if (i > 0)
						html += '<button class="moveUp" onclick="moveRowUp(' + i + ');">Move up</button>';
					html += '</td></tr>';
        }
				
				$("#locations tbody").html(html);
				
				$( "button.delete" ).button({
					icons: { primary: "ui-icon-trash" }
				});
				$( "button.moveDown" ).button({
					icons: { primary: "ui-icon-circle-arrow-s" }
				});
				$( "button.moveUp" ).button({
					icons: { primary: "ui-icon-circle-arrow-n" }
				});
      }

      function ClearPolyLine() {
        points = [];
        BuildPoints();
        ClearRouteDetails();
      }

      function ClearRouteDetails() {
        directionsDisplay.setMap(null);
        directionsDisplay.setPanel(null);
        $("#distance").html("");
        $("#duration").html("");
      }

      function removeRow(index) {
        points.splice(index, 1);
        BuildPoints();
        ClearRouteDetails();
      }

			function moveRowDown(index) {
				var item = points[index];
				points.splice(index, 1);
				points.splice(index+1, 0, item);
				BuildPoints();
        ClearRouteDetails();
			}
			
			function moveRowUp(index) {
				var item = points[index];
				points.splice(index, 1);
				points.splice(index-1, 0, item);
				BuildPoints();
        ClearRouteDetails();
			}
			
      function GetDirections() {
        var directionsDiv = document.getElementById("directions");
        directionsDiv.innerHTML = "Loading...";

        var directions = new google.maps.DirectionsService();
        directionsDisplay.setMap(map);
        directionsDisplay.setPanel(directionsDiv);

        // build array of waypoints (excluding start and end)
        var waypts = [];
        var end = points.length-1;
        var dest = points[end].LatLng;
        
        for (var i=1; i<end; i++) {
          waypts.push({location:points[i].LatLng});
        }

		var travelMode = google.maps.DirectionsTravelMode.DRIVING;
				
        var optimizeRoute = true;
        var request = {
          origin: points[0].LatLng,
          destination: dest,
          waypoints: waypts,
          travelMode: travelMode,
          optimizeWaypoints: optimizeRoute
        };
        
        //Main waypoint request
        directions.route(request, function(result, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            directionsDiv.innerHTML = "";
            directionsDisplay.setDirections(result);

            // calculate total distance and duration
            var distance = 0;
            var time = 0;
            var theRoute = result.routes[0];
            for (var i=0; i<theRoute.legs.length; i++) {
              var theLeg = theRoute.legs[i];
              distance += theLeg.distance.value;
              time += theLeg.duration.value;
            }
            $("#distance").html("Total distance: " + showDistance(distance) + ", ");
            $("#duration").html("total duration: " + Math.round(time/60) + " minutes");
          }
          else {
            var statusText = getDirectionStatusText(status);
            directionsDiv.innerHTML = "An error occurred - " + statusText;
          }
        });
      }
    /* ]]> */
  </script>
